<template>
  <div>
      <page-main class="searchMain">
            <!-- 搜索 -->
            <div class="searchBox">
                <span>搜索</span>
                <el-input v-model="searchValue" class="search" @keyup.enter="searchInputList" placeholder="请输入ID 单位名称或者监管等级"></el-input>
            </div>
      </page-main>
    <page-main>
        <!-- <el-button size="mini" type="primary" @click="addEditSocialUnit">添加</el-button> -->
      <el-table
        :data="tableData"
        :default-sort="{prop: 'id', order: 'ascending'}"
      >

        <el-table-column label="所属单位" prop="unit_full_name">
        </el-table-column>
        <el-table-column label="建筑名称" prop="architecture_name">
        </el-table-column>
        <el-table-column label="地上层数" prop="aboveground_floor">
        </el-table-column>
        <el-table-column label="地下层数" prop="secret_floor"> </el-table-column>
        <el-table-column label="查看详情">
          <template #default="scope">
            <el-button size="mini" type="primary" @click="lookDetails(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #header>
            <el-button size="mini" type="primary" @click="addEditSocialUnit">添加</el-button>
          </template>
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >修改</el-button
            >
            <el-popconfirm
                confirm-button-text="删除"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除？"
                @confirm="del(scope.row)"
                @cancel="cancelEvent">
                <template #reference>
                  <el-button size="mini" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          v-model:currentPage="tableDataInfo.page"
          :page-count="tableDataInfo.total_page"
          :total="tableDataInfo.total"
          layout="total,prev, pager, next, jumper"
          :hide-on-single-page="true"
          background
        >
        </el-pagination>
      </div>
    </page-main>
    <el-dialog
      v-model="dialogFormVisible"
      width="75%"
      @close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="childForm"
        :rules="rules"
        :model="formData"
        label-position="top"
      >
        <el-row>
            <!-- <el-col :offset="1" :span="4">
            <el-form-item label="单位内外饰环境图">
              <el-upload
                :action="upDataUrl + '/unit/upload/upload'"
                list-type="picture-card"
                :headers="upLoadImgHeader"
                :data="upLoadImgData"
                :on-success="headImgUpSuccess"
                limit="1"
                :disabled="disabled"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :offset="1" :span="4">
            <el-form-item label="消防设置屏幕布置图">
              <el-upload
                :action="upDataUrl + '/unit/upload/upload'"
                list-type="picture-card"
                :headers="upLoadImgHeader"
                :data="upLoadImgData"
                :on-success="headImgUpSuccess"
                limit="1"
                :disabled="disabled"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :offset="1" :span="4">
            <el-form-item label="建筑立面图">
              <el-upload
                :action="upDataUrl + '/unit/upload/upload'"
                list-type="picture-card"
                :headers="upLoadImgHeader"
                :data="upLoadImgData"
                :on-success="headImgUpSuccess"
                limit="1"
                :disabled="disabled"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :offset="1" :span="4">
            <el-form-item label="建筑平面图">
              <el-upload
                :action="upDataUrl + '/unit/upload/upload'"
                list-type="picture-card"
                :headers="upLoadImgHeader"
                :data="upLoadImgData"
                :on-success="headImgUpSuccess"
                limit="1"
                :disabled="disabled"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </el-col> -->
          <el-col :span="3" :offset="1">
            <el-form-item label="建筑名称" prop="architecture_name">
              <el-input v-model="formData.architecture_name" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="地上层数" prop="aboveground_floor">
              <el-input v-model="formData.aboveground_floor" :maxlength="3" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="地下层数" prop="secret_floor">
              <el-input v-model="formData.secret_floor" :maxlength="2" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="地址" prop="address">
              <el-input v-model="formData.address" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="地上层面积（m²）" prop="aboveground_area">
              <el-input v-model="formData.aboveground_area" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="3" :offset="1">
            <el-form-item label="地下层面积（m²）" prop="secret_area">
              <el-input v-model="formData.secret_area" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="火灾危险性" prop="fire_hazard">
              <el-select v-model="formData.fire_hazard" filterable placeholder="请选择" :disabled="disabled">
                <el-option
                  v-for="item in fireHazard"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="使用性质" prop="use_nature">
              <el-select v-model="formData.use_nature" filterable placeholder="请选择" :disabled="disabled">
                <el-option
                  v-for="item in useNature"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="建筑类别" prop="building_category">
              <el-select v-model="formData.building_category" filterable placeholder="请选择" :disabled="disabled">
                <el-option
                  v-for="item in buildingCategory"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="建造日期">
              <el-date-picker
                v-model="formData.build_time"
                type="date"
                placeholder="选择日期"
                :disabled="disabled"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="结构类型" prop="structure_type">
              <el-select v-model="formData.structure_type" filterable placeholder="请选择" :disabled="disabled">
                <el-option
                  v-for="item in structureType"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="耐火等级" prop="fire_rating">
              <el-select v-model="formData.fire_rating" filterable placeholder="请选择" :disabled="disabled">
                <el-option
                  v-for="item in storageNature"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="建筑高度（m）" :maxlength="3" prop="building_height">
              <el-input v-model="formData.building_height" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="建筑面积（m²）" prop="building_area">
              <el-input v-model="formData.building_area" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="占地面积（m²）" prop="covere_area">
              <el-input v-model="formData.covere_area" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="标准层面积（m²）" prop="floor_area">
              <el-input v-model="formData.floor_area" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="是否禁用" prop="st">
              <el-switch
                v-model="formData.st"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                :disabled="disabled"
              ></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="总面积（m²）" prop="total_area">
              <el-input v-model="formData.total_area" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="1">
            <el-form-item label="总楼层" :maxlength="3" prop="total_floor">
              <el-input v-model="formData.total_floor" oninput="value=value.replace(/[^\d]/g,'')" :disabled="disabled"></el-input>
            </el-form-item>
          </el-col>
          <!-- 社会单位选择 -->
          <el-col :span="3" :offset="1">
            <el-form-item label="社会单位选择" prop="unit_id">
              <el-select v-model="formData.unit_id" filterable placeholder="请选择" :disabled="disabled">
                <el-option
                  v-for="item in societyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 经纬度 -->
            <el-col :span="7" :offset="1">
            <el-form-item label="单位坐标" prop="longitude">
              <div style="display: flex; align-item: center;">
                <el-input
                  style="width: 30%; margin-right: 1%;"
                  disabled
                  v-model="formData.longitude"
                ></el-input>
                <el-input
                  style="width: 30%; margin-right: 1%;"
                  disabled
                  v-model="formData.latitude"
                ></el-input>
                <!-- <el-button :disabled="disabled" @click="getLatLng">定位</el-button> -->
                <el-button :disabled="disabled" @click="mapIsShow = true">定位</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="5" :offset="1">
            <el-form-item label="网格选择" prop="area_id">
              <el-cascader
                v-model="formData.area_id"
                :options="interLists"
                @change="handleChange"
                :props="cascaderProps"
                :emitPath="false"
                :disabled="disabled"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" :offset="1">
            <el-form-item label="备注" prop="remarks">
              <el-input
                type="textarea"
                placeholder="请输入备注"
                v-model="formData.remarks"
                size="medium"
                show-word-limit
                :disabled="disabled"
               ></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
      <!-- 地图 -->
      <div class="mapBox" v-show="mapIsShow">
          <div class="search">
            <span type="primary">搜索</span>
            <el-input placeholder="请输入内容" v-model="searchInput" @input="inputChange">
                <template #prefix>
                <i class="el-input__icon el-icon-search"></i>
                </template>
            </el-input>
        </div>
        <div id="container"></div>
        <div class="btnBox">
            <el-button type="primary" class="btn" @click="mapIsShow = false">确定</el-button>
            <el-button @click="cancelMap">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 分页 -->
        <el-pagination
        :current-page="pagination.page"
        :total="total"
        :page-size="pagination.size"
        :page-sizes="pagination.sizes"
        :layout="pagination.layout"
        :hide-on-single-page="false"
        class="pagination"
        background
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
  </div>
</template>
<script>
import storage from "@/util/storage";
import { ElMessage } from "element-plus";
// 分页
import paginationMixin from '@/mixins/pagination'
export default {
    // 分页
    mixins: [paginationMixin],
  data() {
    return {
        searchInput: '',
        mapIsShow: false,
        // 总页数
        total: 0,
      cascaderProps: {
        label: "name",
        value: "id",
        children: "sub_item",
        checkStrictly: true,
        leaf:'children'
      },
      // 结构类型
      structureType: [],
    //   火灾危险性
    fireHazard: [],
    // 建筑类别
    buildingCategory: [],
    // 耐火等级
    storageNature: [],
    // 使用性质
    useNature: [],
      societyList: [],
      disabled: false,
      upLoadImgData: {
        type: "image",
      },
      upLoadFlieData: {
        type: "file",
      },
      upDataUrl: import.meta.env.DEV
        ? "/proxy/"
        : import.meta.env.VITE_APP_API_BASEURL,
      tableData: [],
      search: "",
      tableDataInfo: "",
      fatherId: "",
      dialogFormVisible: false,
      formData: {
        architecture_name: "",
        aboveground_floor: "",
        secret_floor: "",
        area_id: "",
        unit_id: '',
        address: '',
        aboveground_area: '',
        longitude: '',
        latitude: '',
        secret_area: '',
        build_time: '',
        fire_hazard: '',
        use_nature: '',
        building_category: '',
        structure_type: '',
        fire_rating: '',
        building_height: '',
        building_area: '',
        covere_area: '',
        floor_area: '',
        st: 0,
        total_area: '',
        total_floor: '',
        // remarks: '',
      },
      rules: {
        architecture_name: [{ required: true, message: "请输入", trigger: "blur" }],
        aboveground_floor: [{ required: true, message: "请输入", trigger: "blur" }],
        secret_floor: [{ required: true, message: "请输入", trigger: "blur" }],
        area_id: [{ required: true, message: "请选择", trigger: "blur" }],
        unit_id: [{ required: true, message: "请选择", trigger: "blur" }],
        address: [{ required: true, message: "请输入", trigger: "blur" }],
        longitude: [{ required: true, message: "请选择", trigger: "blur" }],
        latitude: [{ required: true, message: "请选择", trigger: "blur" }],
        building_height: [{ required: true, message: "请输入", trigger: "blur" }],
        total_area: [{ required: true, message: "请输入", trigger: "blur" }],
        total_floor: [{ required: true, message: "请输入", trigger: "blur" }],
        // remarks: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      id: "",
      pointList: [],
      interLists: [],
      searchValue: '',
    };
  },
  watch: {
      mapIsShow(newData) {
          if (!newData) {
              this.searchInput = ''
          }
      }
  },
  computed: {
    upLoadImgHeader() {
      return {
        "A-Token": this.$store.state.user.a_token,
        "U-Token": this.$store.state.user.u_token,
      };
    },
  },
  created() {
      this.$api.get('/unit/RegionArea/getAreaTree',{query:{
          region_id:this.$store.state.user.user_info.region_id
      }}).then(res=>{
          this.interLists=res.data
      })
    this.fatherId = this.$route.query.id;
    this.$api
      .post("/unit/PatrolPosition/lists", { unit_id: this.$route.query.id })
      .then((res) => {
        this.pointList = res.data.lists;
      });
    this.getDataList();
    this.getSocietyList()
    this.getConfigList()
  },

  methods: {
      inputChange() {
          this.$getMap(this, this.searchInput)
      },
      cancelMap() {
          this.formData.longitude = ''
          this.formData.latitude = ''
          this.mapIsShow = false
      },
    //   获取配置
    getConfigList() {
       this.$api.get('/unit/Setting/Config').then(res => {
         this.structureType = res.data.structure_type
         this.fireHazard = res.data.fire_hazard
         this.buildingCategory = res.data.building_category
         this.storageNature = res.data.storage_nature
         this.useNature = res.data.use_nature
       })
    },
    //   经纬度
      getLatLng() {
      this.$getLocaion(returnCitySN["cip"]).then((res) => {
          let temp = res.data.location.split(',')
        this.formData.longitude=temp[0]//经度
        this.formData.latitude=temp[1]//纬度
      });
    },
      // 获取社会单位列表
    getSocietyList() {
      let user_info = this.$store.state.user.user_info;
      this.$api
        .post("/unit/UnitInformation/lists", {
          region_id: user_info.region_id,
          page: 1,
          rows: 13,
        })
        .then((res) => {
          this.societyList = res.data.lists;
        });
    },
    safeFileUpSuccess(res) {
      this.formData.safe_promise_file = res.data.result;
    },
    orgFileUpSuccess(res) {
      this.formData.org_promise_file = res.data.result;
    },
    imgUpSuccess(res) {
      this.formData.escape_map = res.data.result;
    },
    onExceed() {
      this.$message({
        showClose: true,
        message: "如需更改，请先删除已上传的",
        type: "error",
      });
    },
    getDataList(page) {
    //   let pageNum = 1;
    //   if (page) {
    //     pageNum = page;
    //   }
    let user_info = this.$store.state.user.user_info;
      // 分页
    let query = {
        rows: this.pagination.size,
        page: this.pagination.page,
        region_id: user_info.region_id,
        keywords: this.searchValue
    }
    //   获取列表
      this.$api
        .post("/unit/Building/lists", query)
        .then((res) => {
          this.tableData = res.data.lists;
          this.tableDataInfo = res.data;
          this.total = res.data.total
        });
    },
    // 搜索
    searchInputList() {
        this.getDataList()
    },
    // 删除
    del(data) {
        let query = {
            id: data.id
        }
        this.$api.post('/unit/Building/delete',query).then(res => {
            if (res.code === 200) {
              this.$message({
                    type: 'success',
                    message: res.msg,
                })
          } else {
              this.$message({
                    type: 'error',
                    message: res.msg,
                })
          }
          this.getDataList();
            this.getSocietyList()
        })
    },
    // 点击详情
    lookDetails(row) {
        this.disabled = true
        this.id = row.id;
        this.point_id = row.point_id;
        this.formData = JSON.parse(JSON.stringify(row));
        this.formData.build_time = this.formData.build_time * 1000
        this.dialogFormVisible = true;
        if (row.fire_hazard == '0') {
            this.formData.fire_hazard = ''
        }
        if (row.building_category == '0') {
            this.formData.building_category = ''
        }
        if (row.use_nature == '0') {
            this.formData.use_nature = ''
        }
        if (row.structure_type == '0') {
            this.formData.structure_type = ''
        }
        if (row.fire_rating == '0') {
            this.formData.fire_rating = ''
        }
        if (row.unit_id == '0') {
            this.formData.unit_id = ''
        }
    },
    handleChange(e){
        this.formData.area_id=e[Number(e.length)-1]
    },
    handleEdit(index, row) {
      this.id = row.id;
      this.point_id = row.point_id;
      this.formData = JSON.parse(JSON.stringify(row));
      this.formData.build_time = this.formData.build_time * 1000
      this.dialogFormVisible = true;
      if (row.fire_hazard == '0') {
            this.formData.fire_hazard = ''
        }
        if (row.building_category == '0') {
            this.formData.building_category = ''
        }
        if (row.use_nature == '0') {
            this.formData.use_nature = ''
        }
        if (row.structure_type == '0') {
            this.formData.structure_type = ''
        }
        if (row.fire_rating == '0') {
            this.formData.fire_rating = ''
        }
        if (row.unit_id == '0') {
            this.formData.unit_id = ''
        }
    //   this.getMap(this)
        this.$getMap(this)
    },
    handleSizeChange(e) {},
    handleCurrentChange(e) {
      this.getDataList(e);
    },
    addEditSocialUnit() {
      this.dialogFormVisible = true;
    //   this.getMap(this)
        this.$getMap(this)
    },
    closeDialog() {
      this.$refs.childForm.resetFields();
      let temp = this.formData;
      for (let key in temp) {
        temp[key] = "";
      }
      this.formData = temp;
      this.disabled = false
      this.id = ''
    },
    submitForm() {
      this.$refs.childForm.validate((valid) => {
        if (valid) {
          let region_id = this.$store.state.user.user_info.region_id;
          let data = this.formData;
          data.build_time = new Date(data.build_time).getTime() / 1000
          if (!data.id) {
            data.region_id = region_id;
            this.$api.post("/unit/Building/add", data).then((res) => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: res.msg,
                })
                } else {
                    this.$message({
                        type: 'error',
                        message: res.msg,
                    })
                }
              this.getDataList();
              this.dialogFormVisible = false;
            });
          } else{
              this.$api.post("/unit/Building/edit", data).then((res) => {
                  if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: res.msg,
                })
                } else {
                    this.$message({
                        type: 'error',
                        message: res.msg,
                    })
                }
              this.getDataList();
              this.dialogFormVisible = false;
            });
          }
        } else {
          ElMessage.error("请填写完整");
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss" >
.block {
    display: flex;
    justify-content: center;
}
:deep(.el-textarea__inner) {
    height: 100px;
}
.mapBox {
    z-index: 50;
    width: 800px;
    background-color: rgba(236, 234, 234, 0.938);
    height: 600px;
    position: fixed;
    top: 50%;
    left: 30%;
    transform: translateY(-60%);
    flex-direction: column;
    #container {
        z-index: 100;
        width: 800px;
        height: 500px;
    }
    .btnBox {
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        margin: 0 auto;
        width: 200px;
    }
    .search {
        display: flex;
        span {
            width: 100px;
            background-color: rgb(245, 244, 244);
            line-height: 40px;
            text-align: center;
        }
    }
}
.searchBox {
    display: flex;
    span {
        width: 50px;
        line-height: 40px;
        text-align: center;
    }
    .search {
        width: 30%;
    }
}
.searchMain {
    height: 80px;
}
</style>
